<template>
  <div>
    <el-card>
      <el-form :inline="true" class="form">
        <el-form-item label="用户名：">
          <el-input v-model="keyword" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!keyword.length" @click="search"
            >搜索</el-button
          >
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" @click="addRole">添加权限</el-button>

      <el-table :data="tableData" :border="true">
        <el-table-column align="center" type="index" label="#" />
        <el-table-column align="center" prop="id" label="ID" />
        <el-table-column
          align="center"
          prop="roleName"
          label="角色名称"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="updateTime"
          label="更新时间"
          show-overflow-tooltip
        />
        <el-table-column align="center" label="操作" width="300">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setPromisstion(row)"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateRole(row)"
            >
              编辑
            </el-button>

            <el-popconfirm
              :title="`确定要删除${row.roleName}`"
              width="260px"
              @confirm="deleteUser(row)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper, ->, total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getHasRole"
      />
    </el-card>

    <el-drawer v-model="drawer" title="分配权限" direction="rtl">
      <el-tree
        ref="tree"
        :data="menuArr"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="selectArr"
        :props="defaultProps"
      />
      <template #footer>
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="confirmClick"> 确定 </el-button>
      </template>
    </el-drawer>

    <el-dialog
      v-model="dialogVisible"
      :title="roleParams.id ? '编辑权限' : '新增权限'"
      width="30%"
    >
      <el-form :model="roleParams" :rules="rules" ref="formRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleParams.roleName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermisson,
  reqRemoveRole
  
} from '@/api/acl/role/index'
import type {
  Records,
  RoleResponseData,
  RoleData,
  MenuList,
  MenuResponseData

} from '@/api/acl/role/type'
import { ElMessage } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'
const tableData = ref<Records>([])
const pageNo = ref<number>(1)
const total = ref<number>(0)
const pageSize = ref<number>(5)

const getHasRole = async (pager = 1) => {
  pageNo.value = pager
  const result: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value
  )
  tableData.value = result.data.records
  total.value = result.data.total
}
const handleSizeChange = () => {
  getHasRole()
}
onMounted(() => {
  getHasRole()
})
const dialogVisible = ref<boolean>(false)
const addRole = () => {
  dialogVisible.value = true
  delete roleParams.id
  Object.assign(roleParams, { roleName: '' })
  formRef.value?.clearValidate()
}
const updateRole = (row: RoleData) => {
  dialogVisible.value = true
  Object.assign(roleParams, row)
  formRef.value?.clearValidate()
}

const roleParams = reactive<RoleData>({
  roleName: ''
})
const save = async () => {
  await formRef.value.validate()

  await reqAddOrUpdateRole(roleParams)
  dialogVisible.value = false
  ElMessage({
    type: 'success',
    message: roleParams.id ? '更新成功' : '添加成功'
  })

  getHasRole(roleParams.id ? pageNo.value : 1)
}

const validatorRoleName = (rule: any, value: string, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('角色名称至少输入五位'))
  }
}
const rules = {
  roleName: [{ required: true, validator: validatorRoleName, trigger: 'blur' }]
}
const formRef = ref<any>()

const setPromisstion = async (row: RoleData) => {
  drawer.value = true
  Object.assign(roleParams, row)

  const resule: MenuResponseData = await reqAllMenuList(row.id as number)
  menuArr.value = resule.data
  selectArr.value = filterSelectArr(resule.data, [])
}

const menuArr = ref<MenuList>([])
const selectArr = ref<number[]>([])
const tree = ref<any>()

const confirmClick = async () => {
  const roleId = roleParams.id as number

  const arr = tree.value.getCheckedKeys()
  const arr1 = tree.value.getHalfCheckedKeys()
  const permissionId = [...arr, ...arr1]
  await reqSetPermisson(roleId, permissionId)

  ElMessage({
    type: 'success',
    message: '分配成功'
  })

  drawer.value = false

  getHasRole(pageNo.value)
}

const deleteUser = async (row: RoleData) => {
  await reqRemoveRole(row.id as number)
  ElMessage({
    type: 'success',
    message: '删除成功'
  })

  getHasRole(tableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
}

const keyword = ref<string>('')
const search = () => {
  getHasRole()
  keyword.value = ''
}

import useLayoutSettingStore from '@/store/modules/setting'
const settingStore = useLayoutSettingStore()
const reset = () => {
  settingStore.updateRefresh()
}

const drawer = ref<boolean>(false)
const defaultProps = {
  children: 'children',
  label: 'name'
}

const filterSelectArr = (allData: MenuList, initArr: number[]) => {
  allData.forEach((item) => {
    if (item.level === 4 && item.select) {
      initArr.push(item.id)
    } else if (item.children && item.children.length) {
      filterSelectArr(item.children, initArr)
    }
  })

  return initArr
}
</script>

<style scoped>
.form {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
